<?php
class AreaHelper {
	public static $area_data = null;

	public static function areaKeyExists($key, $areas) {
		foreach($areas as $area) {
			if ($area['key'] == $key) {
				return true;
			}
		}
		return false;
	}

	public static function areaCodeToName($code){
		if ( empty(self::$area_data) ){
			self::$area_data = Config::get('area');
		}
		return isset(self::$area_data[$code])?self::$area_data[$code]: '';
	}


	public static function getProvinceList() {
		if ( empty(self::$area_data) ){
			self::$area_data = Config::get('area');
		}
		$provices = array();
		foreach(self::$area_data as $key => $value) {
			if (preg_match('#^[^0][0-9]0000$#i', $key) != FALSE) {
				$provices[] = ['key' => $key, 'value' => $value];
			}
		}
		return $provices;
	}
	
	public static function getProvinceLetter() {
		if ( empty(self::$area_data) ){
			self::$area_data = Config::get('newarea');
		}
		$provices = array();
		$result = self::$area_data;
		foreach($result as $key1 => $value1) {
			$provices[$key1] = [];
			foreach($result[$key1] as $key2 => $value2) {
				if (preg_match('#^[^0][0-9]0000$#i', $key2) != FALSE) {
					$provices[$key1][] = ['key' => $key2, 'value' => $value2];
				}
			}
		}
		return $provices;
	}

	public static function getCityList($province) {
		if ( empty(self::$area_data) ){
			self::$area_data = Config::get('area');
		}
		$province = substr($province, 0, 2);
		$cities = array();
		foreach(self::$area_data as $key => $value) {
			if (preg_match('#^' . $province . '(0[^0]|[^0]0|[^0][^0])00$#i', $key) != FALSE) {
				$cities[] = ['key' => $key, 'value' => $value];
			}
		}
		return $cities;
	}

	public static function getDistrictList($city) {
		if ( empty(self::$area_data) ){
			self::$area_data = Config::get('area');
		}
		$city = substr($city, 0, 4);
		$districts = array();
		foreach(self::$area_data as $key => $value) {
			if (preg_match('#^' . $city. '(?!00)#i', $key) != FALSE) {
				$districts[] = ['key' => $key, 'value' => $value];
			}
		}
		return $districts;
	}
}